import {PageParams} from '@/types/global.d'
import {partDb} from '@/api/lowdb.ts'
import {Part} from '@/types/part.d'

export const deleteParts = (ids: number[]) => {
  const dbData: Required<Part>[] = partDb.read().value()
  for (let i = dbData.length - 1; i >= 0; i--) {
    if (ids.includes(dbData[i].id)) {
      dbData.splice(i, 1);
    }
  }
  partDb.write()
}

export const updatePart = (data: Part) => {
  const dbData: Part[] = partDb.read().value()
  const index = dbData.findIndex(part=>part.id === data.id)
  if (index !== -1) {
    dbData[index] = data
    partDb.write()
  }
}

export const getPart = (id: number) => {
  return partDb.read().find({ id }).value()
}

export const savePart = (data: Part) => {
  data.id = partDb.read().value().length + 1
  partDb.read().push(data)
      .write()
}

export const listParts = (pageParams: PageParams, part?: Partial<Part>) => {
  let parts: Required<Part>[] = partDb.read().value()
  parts.reverse()
  // 搜索匹配
  let nameCn = part?.nameCn
  if (nameCn) {
    parts = parts.filter(p => p.nameCn.includes(nameCn))
  }
  // 分页
  const startIndex = (pageParams.page - 1) * pageParams.pageSize
  const endIndex = startIndex + pageParams.pageSize
  return {
    records: parts.slice(startIndex, endIndex),
    total: parts.length,
  }
}
